package com.fzu.mmdbproxyframework.model;

import java.io.IOException;
import java.sql.SQLException;

import ch.ethz.ssh2.Session;

public class DataNode {
	public String dataNodeName;
	public String dataNodeuuid;
	public String vmIP;
	public String vmName;
	public String vmPasswd;
	public DBInterf db;
	public  boolean running=false;
	public ch.ethz.ssh2.Connection sshConn;
	
	public void stopmmDBServer() throws SQLException{
		org.h2.tools.Server.shutdownTcpServer("tcp://"+getVmIP()+":"+getDb().getPort()+"", getDb().getPasswd(), true, false);
		this.setRunning(false);
	}
	
	public void startmmDBServer() throws IOException, SQLException{	
		System.out.println("开始启动数据库服务");
			Session session = getssh2Session();
			try {
				session.execCommand("sh /home/xiaozhi/h2/bin/h2.sh");
				this.setRunning(true);
				System.out.println("DataNode = "+getDataNodeName()+"  "+getVmIP()+"的startmmDBServer运行了一次");
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				session.close();
				getSshConn().close();
				
			}
			
	}
	
	public ch.ethz.ssh2.Session getssh2Session() throws IOException{
		setSshConn( creatSSH2Connection(getVmIP(),getVmName(),getVmPasswd()));
		return getSshConn().openSession();
	}
	

	public ch.ethz.ssh2.Connection creatSSH2Connection(String hostIP,String username,String password) throws IOException{
		System.out.println(hostIP+username+password);
		ch.ethz.ssh2.Connection conn = new ch.ethz.ssh2.Connection(hostIP);
		conn.connect(); 
		boolean isAuthenticated = conn.authenticateWithPassword(username, password);

		if (isAuthenticated == false){
			throw new IOException("Authentication failed.");			
		}else{
			return conn;
		}
		
	}

	public String getDataNodeName() {
		return dataNodeName;
	}
	public void setDataNodeName(String dataNodeName) {
		this.dataNodeName = dataNodeName;
	}
//	public String getDataNodeType() {
//		return dataNodeType;
//	}
//	public void setDataNodeType(String dataNodeType) {
//		this.dataNodeType = dataNodeType;
//	}


	public DBInterf getDb() {
		return db;
	}

	public void setDb(DBInterf db) {
		this.db = db;
	}

	public String getVmIP() {
		return vmIP;
	}

	public void setVmIP(String vmIP) {
		this.vmIP = vmIP;
	}

	public String getVmName() {
		return vmName;
	}

	public void setVmName(String vmName) {
		this.vmName = vmName;
	}

	public String getVmPasswd() {
		return vmPasswd;
	}

	public void setVmPasswd(String vmPasswd) {
		this.vmPasswd = vmPasswd;
	}

	public ch.ethz.ssh2.Connection getSshConn() {
		return sshConn;
	}

	public void setSshConn(ch.ethz.ssh2.Connection sshConn) {
		this.sshConn = sshConn;
	}

	public String getDataNodeuuid() {
		return dataNodeuuid;
	}

	public void setDataNodeuuid(String dataNodeuuid) {
		this.dataNodeuuid = dataNodeuuid;
	}

	public  boolean isRunning() {
		return running;
	}

	public  void setRunning(boolean running) {
		this.running = running;
	}


	
}
